package com.itheim.filter;

import com.itheim.util.CurrentHolder;
import com.itheim.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //1.获取请求路径
        String requestURI = request.getRequestURI();

        //2.判断是否是登录请求
        if (requestURI.contains("/login")) {
            //如果是登录请求，直接放行
            filterChain.doFilter(request,response);
            return;
        }

        //3.获取请求头token
        String token = request.getHeader("token");

        //4.判断token是否为空，为空返回错误信息
        if (token==null || token.isEmpty()){
            log.info("请求头token为空");
            response.setStatus(401);
            return;
        }

        //5.校验token是否正确，不正确返回错误信息
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer empid= Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empid);

        } catch (Exception e) {
            log.info("token校验不通过");
            response.setStatus(401);
            return;
        }

        //6.放行
        log.info("请求头token校验通过");
        filterChain.doFilter(request,response);
        CurrentHolder.remove();
    }
}
